﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Cofe.Core.Security;

namespace Cofe.Core
{
    public static class UserFE
    {
        #region Methods
                
        public static void GrantRole(string accountName, string authenticateType, params string[] grantedRole)
        {            
            if (accountName.Contains('?') || accountName.Contains('*'))
                throw new ArgumentException("Account Name cannot contain mask.");

            if (authenticateType.Contains('?') || authenticateType.Contains('*'))
                throw new ArgumentException("Authenticate type cannot contain mask.");

            CofeServices.SecurityManager.UserManager.AddPrincipalPolicy(
                new GenericPrincipalPolicy(grantedRole, authenticateType, accountName, false));
        }

        public static void RevokeRole(Func<IPrincipalPolicy, bool> removeFilter)
        {
            CofeServices.SecurityManager.UserManager.RemovePrincipalPolicy(
                p => p is IPrincipalPolicy && removeFilter(p));
        }

        public static void RevokeRole(string userId, string role)
        {
            RevokeRole((vp) =>
                (vp is GenericPrincipalPolicy) 
                && (vp as GenericPrincipalPolicy).NamePattern == userId
                && (vp as GenericPrincipalPolicy).GrantRole.Contains(role));
        }

        public static void RevokeRole(string userId)
        {
            RevokeRole((vp) =>
                (vp is GenericPrincipalPolicy) && (vp as GenericPrincipalPolicy).NamePattern == userId);
        }

        #endregion

        #region Public Properties

        public static IPrincipal CurrentPrincipal
        {
            get { return CofeServices.SecurityManager.CurrentPrincipal; }            
        }
        #endregion
    }
}
